<template>
  <div class="drag-section">
    <draggable v-model="fileList" @end="onEnd">
      <transition-group>
        <div class="one-list" v-for="(item ,index) in fileList" :key="item[fieldKey]" >
          <a-avatar shape="square" :size="128" :src="item[fieldKey] | _ImgPrefix" @mouseenter="OnMouseEnter(item)" @mouseout="Onmouseout(item)"/>
          <a-button
            v-show="item.showClose"
            class="close"
            shape="circle"
            status="danger"
            size="mini"
            @mouseenter="OnMouseEnter(item)"
            @click="handleDeleteImage(index)"
          >×</a-button>
        </div>
      </transition-group>
    </draggable>
  </div>
</template>
<script>
import draggable from 'vuedraggable'
export default {
  name: 'DragImage',
  components: { draggable },
  props: {
    dataSource: {
      type: Array,
      default: function () {
        return []
      }
    },
    fieldKey: {
      type: String,
      default: 'avatar'
    }
  },
  data () {
    const dataSource = this.dataSource || []
    return {
      fileList: dataSource.map(arg => {
        return Object.assign({}, arg, {
          showClose: false
        })
      })
    }
  },
  watch: {
    dataSource: {
      handler (val) {
        this.fileList = val.map(arg => {
        return Object.assign({}, arg, {
          showClose: false
        })
      })
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 删除图片
    handleDeleteImage (idx) {
      const { fileList } = this
      fileList.splice(idx, 1)
      this.triggerChange(this.fileList)
    },
    // end
    onEnd () {
      this.triggerChange(this.fileList)
    },
    triggerChange (value) {
      this.$emit('change', value)
    },
    OnMouseEnter (item) {
      item.showClose = true
    },
    Onmouseout (item) {
      item.showClose = false
    }
  }
}
</script>
<style lang="less" scoped>
.drag-section{
  &::after{
    content:'';
    display: block;
    clear: both;
  }
  .one-list{
    width: 128px;
    height: 128px;
    float: left;
    margin-right: 20px;
    margin-bottom: 15px;
    position: relative;
    .close{
      font-size: 22px;
      position: absolute;
      right: 2px;
      top: 2px;
      z-index: 2;
      color: #999999;
    }
  }
}
</style>
